<?

if ($_SERVER['SERVER_NAME'] == 'localhost') {
    
    $path = '/';
}
elseif($_SERVER['SERVER_NAME'] == 'dev.gstestequipment.com') {
    
    $path = '/home/mikepaer_v1/dev.gstestequipment.com/';
}


/* How many search results should autocomplete pop up?
 * 
 */
$limiter = 50;

if(!isset($_REQUEST['term'])) {
    exit(0);
}

$term = mysql_escape_string($_REQUEST['term']);

require_once($path . 'includes_php/helpers/functions.php');

/* 1. Search for manufacturers */
$manuRet = array();
$manuFilter = array(
    new DFC(gsLkBrand::FIELD_NAME, $term, DFC::CONTAINS),
    new DFC(gsLkBrand::FIELD_ENABLED, 1, DFC::EXACT)
);

$manuRet = gsLkBrand::findByFilter($db, $manuFilter);
$manuJson = array();

if(count($manuRet) > 0) {
    foreach($manuRet as $return) {
	$link = "browse_by_brand.php?brand=".$return->getId();
	$manuJson[] = array('label' => $return->getName() , 'link' => $link, 'category' => "Manufacturers");
    }
}



/* 2. Search for types */
$manuRet = array();
$manuFilter = array(
    new DFC(gsLkType::FIELD_NAME, $term, DFC::BEGINS_WITH),
    new DFC(gsLkType::FIELD_ENABLED, 1, DFC::EXACT)
);

$manuRet = gsLkType::findByFilter($db, $manuFilter);
$typeJson = array();


if(count($manuRet) > 0) {
    foreach($manuRet as $return) {
	$link = "browse_by_type.php?type=".$return->getId();
	$typeJson[] = array('label' => $return->getName() , 'link' => $link, 'category' => "Equipment");
    }
}

/* Else, look up model numbers.*/

$ret = array();
$filter = array(
    new DFC(gsProducts::FIELD_MODELNO, $term, DFC::BEGINS_WITH),
);
$ret = gsProducts::findByFilter($db, $filter);

$json = array();

$ctr = 0;


foreach($ret as $r) {
    
    if($ctr == $limiter) 
	break;
    
    $brand = lookup_brandById($r->getLkBrand());
    $model = $r->getModelNo();
    
    $label = $brand . ' ' . $model;
    $link = "quote.php?id=".$r->getId();
    
    $json[] = array('label' => $label , 'link' => $link, 'category' => "Products");    
    $ctr++;
}

echo json_encode(array_merge($manuJson, $typeJson, $json));

?>
